<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="width=
  , initial-scale=1.0"
    />
    <title>Document</title>
  </head>
  <body>
    <script src="./lodash.min.js"></script>
    <script>
      function Cart() {
        this.items = this.items||[]
      }
      Cart.prototype.copyDeep = function (arr = []) {
        return _.cloneDeep(arr)
      }

      // 添加商品到购物车
      Cart.prototype.add = function (item) {
     
          // 查找购物车中是否已经存在该商品
          const index = this.items.findIndex((i) => i.id === item.id)
          if (index >= 0) {
            // 已经存在，更新数量
            this.items[index].quantity += item.quantity
          } else {
            // 不存在，添加新商品
            this.items.push(this.copyDeep(item))
          }
       
      }

      // 从购物车中删除商品
      Cart.prototype.del = function (id) {
        const index = this.items.findIndex((i) => i.id === id)
        if (index >= 0) {
          this.items.splice(index, 1)
        }
      }

      // 修改购物车中商品的数量
      Cart.prototype.update = function (id, quantity) {
        const index = this.items.findIndex((i) => i.id === id)
        if (index >= 0) {
          this.items[index].quantity = quantity
        }
      }

      // 计算购物车中所有商品的总价
      Cart.prototype.calculateTotalPrice = function () {
        console.log('计算总价')
        let totalPrice = 0
      
        totalPrice = this.items.reduce(
          (prev, item) => prev + item.price * item.quantity,
          0
        )
        console.log(totalPrice)
  
      }

      // 清空购物车
      Cart.prototype.clear = function () {
        this.items = []
      }

      // 测试代码
      const cart = new Cart()
      const item1 = { id: 1, name: '火鸡面', price: 10, quantity: 2 }
      const item2 = { id: 2, name: '火鸡面', price: 20, quantity: 1 }
      const item3 = { id: 3, name: '火鸡面', price: 10, quantity: 1 }
      const item4 = { id: 1, name: '面包', price: 10, quantity: 1 }

      cart.add(item1)
      cart.add(item2)
      cart.add(item3)

      // 添加重复商品，应该更新数量
      cart.add(item4)

      console.log(cart.items)
      // 删除商品
      cart.del(2)
      console.log(cart.items)

      // 修改商品数量
      cart.update(1, 5)
      console.log(cart.items)

      // 清空购物车
      cart.clear()
      console.log(cart.items)
    </script>
  </body>
</html>
